﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Xml;
using CommonHelp;
using Core.Unity;
using DbHelp;
using Models;
using Newtonsoft.Json;

namespace Services {
    /// <summary>
    /// 卫星云图
    /// </summary>
    public class WXYTInfoService : Core.Unity.IInfoService {
        private EventHandler<ReceivedDataEventArgs> _ReceivedDataEvents;
        private List<WXYTInfo> _DataList;
        /// <summary>
        /// 请求数据的地址
        /// </summary>
        private string _url;
        /// <summary>
        /// 请求数据的上一级地址
        /// </summary>
        private string _parentUrl;

        public event EventHandler<ReceivedDataEventArgs> AfterQueryData {
            add {
                _ReceivedDataEvents += value;
            }
            remove {
                _ReceivedDataEvents -= value;
            }
        }

        public void OnModelCreating(ref DbModelBuilder modelBuilder) {
            modelBuilder.Entity<WXYTInfo>().ToTable("WEBDATA_WXYT");
        }

        public void QueryData() {
            _url = ConfigurationManager.AppSettings["QueryWXYTUrl"].ToString();
            _parentUrl = _url.Substring(0, _url.LastIndexOf('/'));
            HttpHelper http = new HttpHelper(_url);
            http.GetAsync(AfterGetData);
        }

        private void AfterGetData(string responseString) {
            try {
                if (responseString == null) {
                    return;
                }
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(responseString);

                List<WXYTInfo> infos = new List<WXYTInfo>();
                for (int i = 0; i < doc.ChildNodes.Count; i++) {
                    var node = doc.ChildNodes[i];
                    if (node.NodeType == XmlNodeType.XmlDeclaration || node.NodeType == XmlNodeType.Comment) {
                        continue;
                    }
                    foreach (XmlNode item in node.ChildNodes) {
                        string jsonStr = JsonConvert.SerializeXmlNode(item, Newtonsoft.Json.Formatting.None, true);
                        jsonStr = jsonStr.Replace("\"@", "\"");
                        WXYTInfo info = JsonConvert.DeserializeObject<WXYTInfo>(jsonStr);
                        info.ProType = node.Attributes["proType"].Value;
                        info.ID = Guid.NewGuid().ToString();
                        infos.Add(info);
                    }
                }

                _DataList = infos;

                if (_ReceivedDataEvents != null) {
                    _ReceivedDataEvents(this, new ReceivedDataEventArgs(infos));
                }
            }
            catch (Exception ex) {
                CommonHelp.LogHelper.Error(ex);
            }
        }

        public void SaveData(object data) {
            using (WebDataContext db = new WebDataContext()) {
                List<WXYTInfo> list = data as List<WXYTInfo>;
                DbSet<WXYTInfo> infos = db.Set<WXYTInfo>();
                foreach (var item in list) {
                    if (infos.Any(a => a.PicPath == item.PicPath)) {
                        continue;
                    }
                    infos.Add(item);
                    db.SaveChanges();
                    ////下载图片
                    string cacheDir = System.Environment.CurrentDirectory + @"\CacheWXYT";
                    DirectoryInfo dir = new DirectoryInfo(cacheDir);
                    if (!dir.Exists) {
                        dir.Create();
                    }
                    string picFile = cacheDir + @"\" + item.PicPath.Replace("/", "_");
                    string picUrl = _parentUrl + @"/" + item.PicPath;
                    using (WebClient webClient = new WebClient()) {
                        webClient.DownloadFileCompleted += webClient_DownloadFileCompleted;
                        webClient.DownloadFileAsync(new Uri(picUrl, UriKind.Absolute), picFile, new InfoWrapper<WXYTInfo> {
                            CacheFile = picFile,
                            Info = item,
                        });
                    }
                }
            }
        }

        private void webClient_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e) {
            if (e.Error != null) {
                CommonHelp.LogHelper.Error(e.Error);
                return;
            }
            InfoWrapper<WXYTInfo> wrapper = e.UserState as InfoWrapper<WXYTInfo>;
            using (WebDataContext db = new WebDataContext()) {
                DbSet<WXYTInfo> infos = db.Set<WXYTInfo>();
                using (FileStream fs = File.OpenRead(wrapper.CacheFile)) {
                    byte[] imageb = new byte[fs.Length];
                    var row = infos.First(a => a.ID == wrapper.Info.ID);
                    row.Picture = imageb;
                    db.SaveChanges();
                }
            }
            System.IO.File.Delete(wrapper.CacheFile);
        } 
    }
}
